package com.example.saifly.inPageMy;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.OSS.OssHelper;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.saifly.R;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class UserAdviceActivity extends Activity {
    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_useradvice;
    }

    private ImageView ivReturn;
    private ImageView ivAdd;
    private EditText etContent;
    private Button btSubmit;

    private LocalMedia localPath;
    private String ossPath, localUrl;

    private String content;
    //private Timestamp time;
    private boolean isSave=false;
    private boolean judge=false;       //反馈内容必填（判断是否为空）

    private CustomerFeedback customerFeedback=new CustomerFeedback();
    //初始化全局变量，稍后用于退出时清空uid和identity
    private SharedPreferences sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);

    @Override
    protected void init() {
        super.init();

        ivReturn = findViewById(R.id.user_advice_return);
        ivAdd = findViewById(R.id.user_advice_add);
        etContent=findViewById(R.id.user_advice_content);
        btSubmit=findViewById(R.id.user_advice_submit);

        ivReturn.setOnClickListener(new UserAdviceActivity.addListeners());
        ivAdd.setOnClickListener(new UserAdviceActivity.addListeners());
        btSubmit.setOnClickListener(new UserAdviceActivity.addListeners());

    }

    /**
     * 上传到oss的方法,在网络请求函数的一开始调用，也就是RetrofitHelper的之前
     * ossPath=upload();
     */
    private String upload() {
        return OssHelper.uploadImage(UserAdviceActivity.this, localUrl);
    }

    private void initChooseImage() {
        PictureSelector.create(UserAdviceActivity.this)
                .openGallery(PictureMimeType.ofImage())//选择图片资源
                .selectionMode(PictureConfig.SINGLE)//单选图片
                .previewImage(true)//可预览图片
                .isCamera(true)//可拍照
                .enableCrop(true)//允许裁剪
                .compress(true)//压缩
                .withAspectRatio(1, 1)//裁剪比1：1
                .hideBottomControls(false)//显示底部控制栏
                .isGif(false)//不显示gif图
                .freeStyleCropEnabled(true)//可拖拽裁剪框
                .circleDimmedLayer(true)//圆形裁剪框
                .showCropFrame(false)//圆形建议取消边框
                .minimumCompressSize(100)//图片如果小于100kb就不压缩
                .rotateEnabled(true)//可旋转
                .scaleEnabled(true)//可放大缩小
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    localPath = selectList.get(0);
                    // 例如 LocalMedia 里面返回四种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    // 4.media.getAndroidQToPath();为Android Q版本特有返回的字段，此字段有值就用来做上传使用
                    if (localPath.isCompressed()) {
                        localUrl = localPath.getCompressPath();
                    } else if (localPath.isCut()) {
                        localUrl = localPath.getCutPath();
                    } else {
                        localUrl = localPath.getPath();
                    }
                    Glide.with(UserAdviceActivity.this).load(localUrl).into(ivAdd);
                    break;
            }
        }
    }

    private interface submitCustomerFeedback
    {
        @Headers({"Content-Type:application/json"})
        @POST("/manage/submitCustomerFeedback")
        Call<ResponseBody> UserAdviceData(@Body JSONObject jsonObject);
    }

    private void UserAdviceData(CustomerFeedback customerFeedback) {
        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        submitCustomerFeedback apiHomeSetData = retrofit.create(submitCustomerFeedback.class);

        JSONObject jsonObject = new JSONObject();
        String jsonString = JSON.toJSONString(customerFeedback);
        Log.d("userAdvice", "logData: "+jsonString);
        jsonObject.put("customerFeedback",jsonString);
        Log.d("userAdvice", "logData: "+jsonObject);

        Call<ResponseBody> call = apiHomeSetData.UserAdviceData(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            JSONObject result = JSON.parseObject(response.body().string());
            Log.d("啦啦啦啦", "logData: "+result);
            if (result.getInteger("code") == 1) {
                //获取的code为1 说明修改成功
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UserAdviceActivity.this, "反馈成功", Toast.LENGTH_SHORT).show();
                        isSave=true;
                        judge=false;
                        finish();
                    }
                });
            } else {
                //修改错误
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UserAdviceActivity.this, "反馈失败，请重新尝试", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } catch (Exception e) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(UserAdviceActivity.this, "服务器在开小差儿", Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }
    }

    public void Sure () {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if(isSave==false)
        {
            builder.setTitle("确定退出当前界面？");
            builder.setPositiveButton("确定", (dialog, which) -> {
                dialog.dismiss();
                finish();
            })
                    .setNegativeButton("取消", (dialog, which) -> {
                        //取消对话框，返回界面
                        dialog.cancel();
                    }).create().show();
            //只有点击按钮才行，点击空白无用
            builder.setCancelable(false);
        }
        else finish();
    }

    private class addListeners implements View.OnClickListener
    {
        @Override
        public void onClick (View v)
        {
            switch (v.getId())
            {
                case R.id.user_advice_submit:
                    //获得当前用户手机号
                    String phoneNum=sharedPreferences.getString("uid","default");
                    customerFeedback.setPatientPhone(phoneNum);
                    //Log.d("***", "手机号： "+phoneNum);

                    //获得反馈内容
                    content=etContent.getText().toString().trim();
                    if(content.length()!=0)
                    {
                        customerFeedback.setContent(content);
                        judge=true;
                        Log.d("***", "内容： "+content);
                    }
                    else
                    {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(UserAdviceActivity.this, "您还未填入反馈内容", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    //获得系统时间
                    //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
                    //Date date = new Date(System.currentTimeMillis());
                    //time=simpleDateFormat.format(date);

                    Timestamp date= new Timestamp(new Date().getTime());
                    customerFeedback.setDate(date);
                    //Log.d("***", "时间： "+date);

                    if(localUrl==null){
                        customerFeedback.setPicture("unexistedPicture");
                    }
                    else{
                        //获得反馈图片路径
                        String ossPath=OssHelper.uploadImage(UserAdviceActivity.this,localUrl);
                        customerFeedback.setPicture(ossPath);
                        Log.d("***", "图片： "+ossPath);
                    }

                    if(judge==true)
                    {
                        new Thread(new Runnable() {
                            @Override
                            public void run()
                            {
                                UserAdviceData(customerFeedback);
                            }
                        }).start();
                    }
                    break;
                case R.id.user_advice_return:
                    Sure();
                    break;
                case R.id.user_advice_add:
                    initChooseImage();
                    break;
                default:
                    break;
            }
        }
    }
}
